<?php

/* * 系统权限配置，用户角色管理
 * Some rights reserved：abc3210.com
 * Contact email:admin@abc3210.com
 */

class RbacAction extends AdminbaseAction {

    protected $User, $Role, $Access, $Node, $Role_user;

    function _initialize() {
        parent::_initialize();
        $this->Role = D("Role");
        $this->Access = D("Access");
        $this->Node = D("Node");
        $this->Role_user = D("Role_user");
    }

    /**
     * 角色管理，有add添加，edit编辑，delete删除
     */
    public function rolemanage() {
        $data = $this->Role->order(array("listorder" => "asc", "id" => "desc"))->select();
        $this->assign("data", $data);
        $this->display();
    }

    /**
     * 添加角色
     */
    public function roleadd() {
        if ($this->isPost()) {
            if ($this->Role->create()) {
                if ($this->Role->add()) {
                    $jumpUrl = U("Rbac/rolemanage");
                    $this->assign("jumpUrl", $jumpUrl);
                    $this->success("添加角色成功！");
                } else {
                    $this->error("添加失败！");
                }
            } else {
                $this->error($this->Role->getError());
            }
        } else {
            $this->display();
        }
    }

    /**
     * 删除角色
     */
    public function roledelete() {
        $id = (int) $this->_get("id");
        if ($id == 1) {
            $this->error("超级管理员角色不能被删除！");
        }
        $status = $this->delete($this->Role);
        if ($status) {
            $this->assign("jumpUrl", U('Rbac/rolemanage'));
            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }

    /**
     * 编辑角色
     */
    public function roleedit() {
        $id = (int) $this->_get("id");
        if ($id == 0) {
            $id = (int) $this->_post("id");
        }
        if ($id == 1) {
            $this->error("超级管理员角色不能被修改！");
        }
        if ($this->isPost()) {
            $status = $this->updata($this->Role);
            if ($status) {
                $this->assign("jumpUrl", U('Rbac/rolemanage'));
                $this->success("修改成功！");
                exit;
            } else {
                $this->error($this->Role->getError());
            }
        }
        $data = $this->edit($this->Role);
        if ($data == false) {
            $this->error("该角色不存在！");
        }
        $this->assign("data", $data);
        $this->display();
    }

    /**
     * 显示项目
     */
    public function purview() {
        $data = $this->Node->where(array("pid" => 0, "level" => 1))->select();
        $this->assign("data", $data);
        $this->display();
//
//        $data = $this->Purview->nodebind();
//        foreach ($data as $k => $v) {
//            $data[$k]['parentid'] = $data[$k]['pid'];
//            $data[$k]['status_html'] = $data[$k]['status'] == 1 ? "启用" : "关闭";
//            $data[$k]['operate'] = '<a href="' . U('Rbac/pur_node', array('id' => $data[$k]['id'])) . '">权限赋予</a> | <a href="' . U('Rbac/editpur', array('id' => $data[$k]['id'])) . '">修改</a> | <a href="javascript:confirmurl(\'' . U("Rbac/delpur", array("id" => $data[$k]["id"])) . '\',\'确认要删除 『 ' . $data[$k]['title'] . ' 』 吗？\')">删除</a>';
//        }
//        import('@.ORG.Util.Tree');
//        $Tree = new Tree();
//        $Tree->init($data);
//        $Tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
//        $Tree->nbsp = '&nbsp;&nbsp;&nbsp;';
//        $str = "<tr>
//	   <td align='center'>\$id</td>
//	   <td >\$spacer\$title</td>
//	   <td align='center'>\$status_html</td>
//	   <td align='center' >\$operate</td>
//         </tr>";
//        $categorys = $Tree->get_tree(0, $str);
//        $this->assign("alisthtml", $categorys);
//        $this->display();
    }

    /**
     * 添加项目
     */
    public function addpur() {
        if ($this->isPost()) {
            $data = $this->Node->create();
            if ($data) {
                if ($this->Node->add($data)) {
                    $this->assign("jumpUrl", U('Rbac/purview'));
                    $this->success("添加成功！");
                } else {
                    $this->error("添加失败！");
                }
            } else {
                $this->error($this->Node->getError());
            }
        } else {
            $this->display();
        }
    }

    /**
     * 编辑项目
     */
    public function editpur() {
        if ($this->isPost()) {
            $data = $this->Node->create();
            if ($data) {
                if ($this->Node->save($data)) {
                    $this->assign("jumpUrl", U('Rbac/purview'));
                    $this->success("编辑成功！");
                } else {
                    $this->error("编辑失败！");
                }
            } else {
                $this->error($this->Node->getError());
            }
        } else {
            $id = $this->_get("id");
            $data = $this->Node->where(array("id" => $id))->find();
            $this->assign("data", $data);
            $this->display();
        }
    }

    /**
     * 删除
     */
    public function delpur() {
        $id = $this->_get('id');
        if (!$id) {
            $id = $this->_post('id');
        }
        $data = $this->Node->where(array("id" => $id))->find();
        if ($data) {
            $count = $this->Node->where(array("pid" => $id))->count();
            if ($count == 0) {
                if ($this->Node->where(array("id" => $id))->delete()) {
                    $this->assign("jumpUrl", U('Rbac/purview'));
                    $this->success("删除成功！");
                } else {
                    $this->error("删除失败！");
                }
            } else {
                $this->error("删除权限控制节点只能从最底层删起！");
            }
        } else {
            $this->error('删除的信息不存在！');
        }
    }

    /**
     * 权限列表
     */
    public function purlist() {
        if ($this->isPost()) {
            $operate = $this->_post("operate");
            if ($operate == "add") {
                $name = $this->_post("name");
                $validate = array(
                    array('name', '', '该项目/模块/方法已经存在！', 0, 'unique', 1)
                );
                if ($name != "*") {
                    $count = $this->Node->where(array("name" => $name, "pid" => $this->_post("pid")))->select();
                    if ($count > 0) {
                        $this->error("该项目/模块/方法已经存在！");
                    }
                }
                $data = $this->Node->create();
                if ($data) {
                    if ($this->Node->add($data)) {
                        $this->assign("jumpUrl", U('Rbac/purview'));
                        $this->success("添加成功！");
                    } else {
                        $this->error("添加失败！");
                    }
                } else {
                    $this->error($this->Node->getError());
                }
            } else if ($operate == "edit") {
                $data = $this->Node->create();
                if ($data) {
                    if ($this->Node->save($data)) {
                        $this->assign("jumpUrl", U('Rbac/purview'));
                        $this->success("编辑成功！");
                    } else {
                        $this->error("编辑失败！");
                    }
                } else {
                    $this->error($this->Node->getError());
                }
            } else if ($operate == "delete") {
                $this->delpur();
            } else {
                $this->error("没指定操作！");
            }
        } else {
            $pid = $this->_get("id");
            $app = $this->Node->where(array("id" => $pid))->find();
            $data = $this->Node->node();
            $data = $this->Node->child($pid, $data);
            $this->assign("app", $app);
            $this->assign("data", $data);
            $this->display();
        }
    }

    /**
     * 角色授权
     */
    public function authorize() {
        if ($this->isPost()) {
            //角色ID
            $roid = $this->_post("roid");
            //权限节点数组
            $menuid = $_POST['menuid'];
            foreach ($menuid as $k => $v) {
                $node = $this->Node->field(array("id,level,pid"))->where(array("id" => $v))->find();
                $data[] = array(
                    "role_id" => $roid,
                    "node_id" => $v,
                    "level" => $node['level'],
                    "pid" => $node['pid']
                );
            }
            if (!is_array($data)) {
                $delete = $this->Access->where(array("role_id" => $roid))->delete();
                if ($delete) {
                    $this->success("已经取消全部授权！");
                    exit;
                } else {
                    $this->error("授权失败！");
                }
            }
            //开启事物
            $this->Access->startTrans();
            $delete = $this->Access->where(array("role_id" => $roid))->delete();
            if ($this->Access->addAll($data)) {
                //提交事物
                $this->Access->commit();
                $this->success("授权成功！");
            } else {
                //事物回滚
                $this->Access->rollback();
                $this->error("授权失败！");
            }
        } else {
            $roid = $this->_get("id");
            if (empty($roid)) {
                $this->error("参数不正确！");
            }
            $data = $this->Role->where(array("id" => $roid))->find();
            if (!$data) {
                $this->error("对应角色不存在！");
            }
            //获取access表中对应的权限
            $accress = $this->Access->where(array("role_id" => $roid))->select();
            $this->assign("accrbac", $accress);
            //获取role表中全部权限项
            $xm = $this->Node->where(array("level" => 1, "status" => 1))->select();
            foreach ($xm as $key => $value) {
                $acf = $this->Access->where(array("role_id" => $roid, "node_id" => $xm[$key]['id']))->count();
                $xm[$key]['acc'] = $acf > 0 ? 1 : 0;
                $xm[$key]['mok'] = $this->Node->where(array("pid" => $xm[$key]['id']))->select();
                foreach ($xm[$key]['mok'] as $i => $v) {
                    $acf = $this->Access->where(array("role_id" => $roid, "node_id" => $xm[$key]['mok'][$i]['id']))->count();
                    $xm[$key]['mok'][$i]['acc'] = $acf > 0 ? 1 : 0;
                    $xm[$key]['mok'][$i]['jied'] = $this->Node->where(array("pid" => $xm[$key]['mok'][$i]['id']))->select();
                    foreach ($xm[$key]['mok'][$i]['jied'] as $ii => $vv) {
                        $acf = $this->Access->where(array("role_id" => $roid, "node_id" => $xm[$key]['mok'][$i]['jied'][$ii]['id']))->count();
                        $xm[$key]['mok'][$i]['jied'][$ii]['acc'] = $acf > 0 ? 1 : 0;
                    }
                }
            }
            $this->assign("roid", $roid);
            $this->assign("group", $group);
            $this->assign("xm", $xm);
            $this->display();
        }
//        if ($this->isPost()) {
//            //角色ID
//            $id = $this->_post("id");
//            //权限节点数组
//            $menuid = $_POST['menuid'];
//            foreach ($menuid as $k => $v) {
//                $node = $this->Node->field(array("id,level,pid"))->where(array("id" => $v))->find();
//                $data[] = array(
//                    "role_id" => $id,
//                    "node_id" => $v,
//                    "level" => $node['level'],
//                    "pid" => $node['pid']
//                );
//            }
//            if (!is_array($data)) {
//                $delete = $this->Access->where(array("role_id" => $id))->delete();
//                if ($delete) {
//                    $this->success("已经取消全部授权！");
//                    exit;
//                } else {
//                    $this->error("授权失败！");
//                }
//            }
//            //开启事物
//            $this->Access->startTrans();
//            $delete = $this->Access->where(array("role_id" => $id))->delete();
//            if ($this->Access->addAll($data)) {
//                //提交事物
//                $this->Access->commit();
//                $this->success("授权成功！");
//            } else {
//                //事物回滚
//                $this->Access->rollback();
//                $this->error("授权失败！");
//            }
//        } else {
//            $id = $this->_get("id");
//            $data = $this->Node->nodebind();
//            import('@.ORG.Util.Tree');
//            foreach ($data as $k => $v) {
//                $data[$k]['parentid'] = $data[$k]['pid'];
//                $data[$k]['checked'] = $this->Node->is_checked($id, $data[$k]['id']) ? "checked" : "";
//                $data[$k]['parentid_node'] = ($data[$k]['parentid']) ? ' class="child-of-node-' . $data[$k]['parentid'] . '"' : '';
//
////                $sdata[$v['id']]=$v;
////                $sdata[$v['id']]['parentid'] = $data[$k]['pid'];
////                $sdata[$v['id']]['checked'] = $this->Node->is_checked($id,$data[$k]['id'])?"checked":"";
////                $sdata[$v['id']]['parentid_node'] = ($data[$k]['parentid'])? ' class="child-of-node-'.$data[$k]['parentid'].'"' : '';
//            }
//            $str = "<tr id='node-\$id' \$parentid_node>
//	        <td style='padding-left:30px;'>\$spacer<input type='checkbox' name='menuid[]' value='\$id' level='\$level' \$checked onclick='javascript:checknode(this);'> \$title</td>
//            </tr>";
//            $Tree = new Tree();
//            $Tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
//            $Tree->nbsp = '&nbsp;&nbsp;&nbsp;';
//            $Tree->init($data);
//            $categorys = $Tree->get_tree(0, $str, $id);
//            //print_r($categorys);exit;
//            $this->assign("id", $this->_get("id"));
//            $this->assign("alist", $categorys);
//            $this->display();
//        }
    }

    public function listorders() {
        $status = parent::listorders($this->Role);
        if ($status) {
            $this->success("排序更新成功！");
        } else {
            $this->error("排序更新失败！");
        }
    }

    /**
     * 设置栏目权限 
     */
    public function setting_cat_priv() {
        if ($this->isPost()) {
            $roleid = $this->_post("roleid");
            $priv = array();
            foreach($_POST['priv'] as $k=>$v){
                foreach($v as $e=>$q){
                    $priv[] = array("roleid"=>$roleid,"catid"=>$k,"action"=>$q,"is_admin"=>1);
                }
            }
            //设置权限前，先删除原来旧的权限
            M("Category_priv")->where(array("roleid"=>$roleid))->delete();
            //添加新的权限数据，使用D方法有操作记录产生
            D("Category_priv")->addAll($priv);
            $this->success("权限赋予成功！");
        } else {
            import('@.ORG.Util.Tree');
            $roleid = $this->_get("roleid");
            $categorys = F("Category");
            $tree = new Tree();
            $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
            $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
            $category_priv = M("Category_priv")->where(array("roleid"=>$roleid))->select();
            $priv = array();
            foreach($category_priv as $k=>$v){
                $priv[$v['catid']][$v['action']] = true;
            }
            
            foreach ($categorys as $k => $v) {
                if ($v['type'] == 1 || $v['child']) {
                    $v['disabled'] = 'disabled';
                    $v['init_check'] = '';
                    $v['add_check'] = '';
                    $v['delete_check'] = '';
                    $v['listorder_check'] = '';
                    $v['push_check'] = '';
                    $v['move_check'] = '';
                } else {
                    $v['disabled'] = '';
                    $v['add_check'] = isset($priv[$v['catid']]['add']) ? 'checked' : '';
                    $v['delete_check'] = isset($priv[$v['catid']]['delete']) ? 'checked' : '';
                    $v['listorder_check'] = isset($priv[$v['catid']]['listorder']) ? 'checked' : '';
                    $v['push_check'] = isset($priv[$v['catid']]['push']) ? 'checked' : '';
                    $v['move_check'] = isset($priv[$v['catid']]['remove']) ? 'checked' : '';
                    $v['edit_check'] = isset($priv[$v['catid']]['edit']) ? 'checked' : '';
                }
                $v['init_check'] = isset($priv[$v['catid']]['init']) ? 'checked' : '';
                $categorys[$k] = $v;
            }
            $str = "<tr>
	<td align='center'><input type='checkbox'  value='1' onclick='select_all(\$catid, this)' ></td>
	<td>\$spacer\$catname</td>
	<td align='center'><input type='checkbox' name='priv[\$catid][]' \$init_check  value='init' ></td>
	<td align='center'><input type='checkbox' name='priv[\$catid][]' \$disabled \$add_check value='add' ></td>
	<td align='center'><input type='checkbox' name='priv[\$catid][]' \$disabled \$edit_check value='edit' ></td>
	<td align='center'><input type='checkbox' name='priv[\$catid][]' \$disabled \$delete_check  value='delete' ></td>
	<td align='center'><input type='checkbox' name='priv[\$catid][]' \$disabled \$listorder_check value='listorder' ></td>
	<td align='center'><input type='checkbox' name='priv[\$catid][]' \$disabled \$push_check value='push' ></td>
	<td align='center'><input type='checkbox' name='priv[\$catid][]' \$disabled \$move_check value='remove' ></td>
            </tr>";
            $tree->init($categorys);
            $categorydata = $tree->get_tree(0, $str);
            $this->assign("categorys", $categorydata);
            $this->assign("roleid", $roleid);
            $this->display("categoryrbac");
        }
    }

}

?>
